package com.hcloud.auth.api.permission;

import com.hcloud.common.core.constants.AuthConstants;
import com.hcloud.system.api.bean.user.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.Collection;

/**
 * @Auther hepangui
 * @Date 2018/11/14
 */
@Slf4j
@Service("ACS")
public class AuthorityCheckService {

    public boolean has(String authority){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return false;
        }
        Object principal = authentication.getPrincipal();
//        if(principal instanceof User){
//            String account = ((User) principal).getAccount();
//            if("hepg".equals(account)){
//                return true;
//            }
//        }
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        long count = authorities.stream().dropWhile(grantedAuthority -> grantedAuthority.getAuthority().equals(authority)).count();
        return count>0;
//
//        for (GrantedAuthority grantedAuthority : authorities) {
//            String authority1 = grantedAuthority.getAuthority();
//            if(authority1!=null && authority1.equals(authority)){
//                return true;
//            }
//        }
//        return false;
    }
}
